package ups.MapParse;

import java.util.ArrayList;
import java.io.File;

import ups.Common.Ship;

public class ShipFinder {
	/* Finds the ships in a given image file */
	ArrayList<Ship> _ships;
	
	public ShipFinder( File imageFile, ArrayList<LetterPattern> letterPatterns, ArrayList<String> shipNames ) throws Exception {
		// First we let our handy TextFinder go through the Image
		TextFinder finder = new TextFinder( imageFile, letterPatterns, shipNames );
		
		ArrayList<PositionedString> results = finder.positionedStrings();
		
		_ships = new ArrayList<Ship>();
		
		/* 1st Pass to Seperate Our Ship Icons and Our Text */
		ArrayList<PositionedString> ships = new ArrayList<PositionedString>();
		ArrayList<PositionedString> text =  new ArrayList<PositionedString>();
		int strIdx;
		for( strIdx = 0; strIdx < results.size(); strIdx++ ) {
			PositionedString s = results.get( strIdx );
			if( s.getString().equals( "0" ) || s.getString().equals("1" )) {
				ships.add( s );
			} else {
				text.add( s );
			}
		}
		
		double lowestDistance;
		PositionedString closestMarkerString = null;
		for( PositionedString shipName : text ) {
			lowestDistance = Double.MAX_VALUE;
			Point closestIconLocation = new Point(0,0);
			/* Find Closest Ship Icon To Name That has Same Status*/
			for( PositionedString shipIcon : ships ) {
				if(( shipName.getColor().equals(Pixel.bluePixel) && shipIcon.getString().equals( "1" )) ||
					( shipName.getColor().equals(Pixel.redPixel) && shipIcon.getString().equals( "0" ))) {
					double distance = shipName.getLocation().distanceFrom( shipIcon.getLocation() );
					if( distance < lowestDistance ) {
						//System.out.println(shipName.getLocation().toString() + " is " + distance + " from " + shipIcon.getLocation().toString() );
						lowestDistance = distance;
						closestIconLocation = shipIcon.getLocation();
						closestMarkerString = shipIcon;
					}
				}
			}
			
			// HACK: Sometimes we can't find the ship, in which case we need to just keep the location of the text!
			if( lowestDistance < 60 ) {
				shipName.setLocation( closestIconLocation );	
			}
			
			if( closestMarkerString.getString().equals( "1" )) {
				_ships.add( new Ship( shipName.getString(), shipName.getLocation(), true, 0  ));
			} else {
				_ships.add( new Ship( shipName.getString(), shipName.getLocation(), false, 0  ));
			}
		}		
	}
	
	
	public ArrayList<Ship> getShips() {
		return _ships;
	}
}
